<template>
  <div class="permission">
    <el-card class="box-card">
      <div class="btnbox">
        <el-button type="primary" size="mini" @click="openAdd(1, 0)">
          <i class="el-icon-edit"></i>添加菜单
        </el-button>

        <el-table :data="permissionList" row-key="id">
          <el-table-column label="菜单名称" prop="name"></el-table-column>
          <el-table-column label="权限标识" prop="code"></el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                @click="openAdd(2, row.id)"
                v-if="row.type === 1"
                >添加权限</el-button
              >
              <el-button type="text">查看api权限</el-button>
              <el-button type="text" @click="openEdit(row.id)">查看</el-button>
              <el-button type="text" @click="delPermission(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <mypanel
        ref="mypanel"
        :showDialog.sync="showDialog"
        @updateData="getAllPermission"
      ></mypanel>
    </el-card>
  </div>
</template>

<script>
import { delPermissionApi, getAllPermissionApi } from "@/api/permission.js";

export default {
  data() {
    return {
      // 面板的显示与隐藏
      showDialog: false,
      // 权限列表
      permissionList: [],
    };
  },
  methods: {
    // 打开新增面板
    openAdd(type, pid) {
      // 打开面板
      this.showDialog = true;
      // 调用子组件中的getData方法
      this.$refs.mypanel.getData(type, pid);
    },
    // 打开编辑面板
    openEdit(id) {
      this.showDialog = true;
      // 调用子组件中的获取数据的方法
      this.$refs.mypanel.getDetailPermission(id);
    },
    async delPermission(id) {
      try {
        // 询问是否删除
        await this.$confirm("是否删除数据", "提示");
        // 调用删除的接口
        await delPermissionApi(id);
        //  console.log(res);
        // 提示删除成功
        this.$message.success("删除成功");
        // 更新数据
        this.getAllPermission();
      } catch (error) {
        // 提示删除失败
        this.$message.error("删除失败");
      }
    },
    // 获取所有权限点
    async getAllPermission() {
      const res = await getAllPermissionApi();
      console.log(res);
      this.permissionList = this.trunData(res.data, "0");
    },
    // 定义一个转换树状结构数据的方法
    trunData(arr, pid) {
      const res = [];
      arr.forEach((item) => {
        if (item.pid === pid) {
          const son = this.trunData(arr, item.id);
          if (son.length > 0) {
            item.children = son;
          }
          res.push(item);
        }
      });
      return res;
    },
  },

  created() {
    this.getAllPermission();
  },
  components: {
    mypanel: () => import("./components/panel.vue"),
  },
};
</script>

<style lang="scss">
.permission {
  margin: 20px;
  .btnbox {
    text-align: right;
  }
}
</style>
